/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.login.controller;

import java.util.Locale;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import offset.nodes.server.controller.AttributeConstants;
import offset.nodes.server.controller.RepositoryPlugIn;
import offset.nodes.server.model.UserInfo;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Walter L�tgenau
 */
public class LoginAction extends Action {
    
    /** Creates a new instance of LoginAction */
    public LoginAction() {
    }
    
    public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception {
        LoginForm loginForm = (LoginForm) form;
        
        if ( loginForm.getUserName() == null || loginForm.getPassword() == null)
            return mapping.findForward("login");
        
        Repository repository = RepositoryPlugIn.getRepository();
        
        Session session = repository.login(
            new SimpleCredentials(loginForm.getUserName(), loginForm.getPassword().toCharArray()));
        
        // todo: find user in repository, authentify user
        UserInfo user = new UserInfo();
        user.setLocale(Locale.getDefault());
        if ( loginForm.getUserType().equals(LoginForm.USERTYPE_APPLET))
            user.setType(UserInfo.TYPE_APPLET);
        
        request.getSession().setAttribute( AttributeConstants.ATT_REPOSITORY_SESSION, session);
        request.getSession().setAttribute( AttributeConstants.ATT_USER_INFO, user);
        
        return (ActionForward) request.getSession().getAttribute(AttributeConstants.ATT_LOGIN_FORWARD);
    }
    
    
}
